<?php

require_once __DIR__ . '/vendor/autoload.php';

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class Hook
{
    protected $request;
    protected $response;
    protected $platform;
    protected $result = [];

    public function __construct()
    {
        $this->request = Request::createFromGlobals();
        $this->response = new Response();
        $this->platform = $this->request->segment(2);
    }

    public function handle()
    {
        if($this->platform){
            $args = $this->request->segments();
            $this->{$this->platform}(...array_slice($args, 2));
        }else{
            $this->msg('Not Found')->code(404);
        }
        
        $this->response
            ->setContent(json_encode($this->result))
            ->headers->set('Content-Type', 'application/json');
        $this->response->send();
    }

    protected function msg($message)
    {
        $this->result['msg'] = $message;
        return $this;
    }

    protected function data($data)
    {
        $this->result['data'] = $data;
        return $this;
    }

    protected function code($code = 200)
    {
        $this->response->setStatusCode($code);
        return $this;
    }

    public function gitee($event)
    {
        if ($this->request->isMethod('POST')) {
            if($this->request->headers->get('User-Agent') === 'git-oschina-hook'){
                exec("git pull",$out);
                print_r($out);
                die();
            }else{
                $this->msg('Invalid platform')->code(500);
            }
        } else {
            $this->msg('Invalid request method')->code(500);
        }
    }
    
}

(new Hook())->handle();

// hahahhahaha





